package com.mingzhi.lotterysystem.controller.handler;

import com.mingzhi.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import com.mingzhi.lotterysystem.common.exception.ControllerException;
import com.mingzhi.lotterysystem.common.exception.ServiceException;
import com.mingzhi.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice //可以捕获全局抛得异常
public class GlobalExceptionHandler {

    //打印日志
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceException(ServiceException e) {
        //打印日志
        logger.warn("ServiceException:{}",e);

        //构造错误的结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMassage());
    }

    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e) {
        //打印日志
        logger.warn("ControllerException:{}",e);

        //构造错误的结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMassage());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> exception(Exception e) {
        //打印日志
        logger.warn("Exception:{}",e);

        //构造错误的结果
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }
}
